<template>
  <el-form ref="formRef" :model="formData" label-width="120px" :rules="rules">
    <base-layout
      :dialog-close-confirm="false"
      :dialog-title="dialogTitle"
      :dialog-visible="dialogVisible"
      visibleContent2
      @dialog-close="dialogClose"
    >
      <template #searchPanel>
        <el-row>
          <el-col :span="12">入库单基础信息</el-col>
        </el-row>
        <el-divider></el-divider>
        <el-row>
          <el-col :span="6">
            <el-form-item label="入库编号" prop="coinStorageCodede">
              <el-input
                v-model="formData.inStorageCode"
                readonly="readonly"
                disabled
                placeholder="自动生成"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="入库门店" prop="storeId">
              <job-shop
                v-model="formData.storeId"
                defaultStoreId
                class="w-100"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="入库仓库" prop="storageId">
              <el-select
                v-model="formData.storageId"
                placeholder="请选择"
                @change="requestStorageSiteList"
                class="w-100"
              >
                <el-option
                  v-for="item in storageList"
                  :key="item.id"
                  :value="item.id"
                  :label="item.storageName"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item
              v-if="formData.inStorageType == '采购入库'"
              label="供应商"
              prop="supplierId"
            >
              <el-select
                v-model="formData.supplierId"
                placeholder="请选择"
                class="w-100"
                @change="supplierChange"
              >
                <el-option
                  v-for="item in supplierList"
                  :key="item.id"
                  :value="item.id"
                  :label="item.supplierName"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="单据日期" prop="receiptsTime">
              <el-date-picker
                v-model="formData.receiptsTime"
                type="datetime"
                disabled
                placeholder="请选择"
                class="w-100"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="入库类型" prop="inStorageType">
              <el-select
                v-model="formData.inStorageType"
                clearable
                placeholder="请选择"
              >
                <el-option
                  v-for="item in dict['精品入库类型']"
                  :key="item.index"
                  :value="item.value"
                  :label="item.text"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item
              v-if="formData.inStorageType != '其他入库'"
              label="来源单号" prop="workOrderCode">
              <el-input
                v-model="formData.workOrderCode"
                placeholder="请输入"
                @blur="sourceCodeBlur"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="采购备注" prop="remark">
              <el-input
                type="textarea"
                v-model="formData.remark"
                :rows="6"
                placeholder="请输入"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </template>
      <template #contentPanel>
        <el-row>
          <el-col :span="12">入库负责人员</el-col>
        </el-row>
        <el-divider></el-divider>
        <el-row>
          <el-col :span="6">
            <el-form-item label="入库负责人" prop="userName">
              <user-select
                v-model="formData.userName"
                :store-id="formData.storeId"
                @change="userNameHChange"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="联系方式" prop="phone">
              <el-input v-model="formData.phone" placeholder="请输入" />
            </el-form-item>
          </el-col>
        </el-row>
      </template>
      <template #contentPanel2>
        <el-row type="flex" align="middle">
          <el-col :span="12">入库精品列表</el-col>
          <el-col class="text-right" :span="12">
            <el-button
              type="primary"
              icon="el-icon-plus"
              @click="addProductHandle"
              v-show="formData.inStorageType == '其他入库'"
              >添加入库精品</el-button
            >
          </el-col>
        </el-row>
        <el-divider></el-divider>
        <!-- @size-change="handleSizeChange"
          @current-change="handleCurrentChange" -->
        <data-table
          has-action
          :is-show-page="false"
          :value="formData.partsList"
          :table-column-attributes="tableColumns"
          :width="160"
        >
          <template #action="{row, $index}">
            <i
              class="el-icon-delete"
              title="删除"
              style="cursor: pointer;"

              @click="handleDataDelete(row, $index)"
            ></i>
          </template>
          <div class="total-count" slot="allNum">
            精品总金额:<span class="money-value">￥{{formData.amount}}</span>
            <span class="ml-20">精品总数:</span
            ><span class="count-value">{{formData.partsTotal}}</span>
          </div>
        </data-table>
        <div class="text-right mt-10">
          <span class="total-count">
            入库总金额:<span class="money-value">￥{{formData.amount}}</span>
          </span>
          <el-button v-permission="$route.params.id == 0 ? authConfig.add : authConfig.edit" class="ml-20" type="success" @click="submitHandle"
            >{{$route.params.id == 0 ? '新增' : '更新'}}入库单</el-button
          >
        </div>
      </template>
      <template #dialog>
        <select-product-form v-if="showProductTable" @select="confirmSelectHandle" :supplier-id="formData.supplierId" />
      </template>
    </base-layout>
  </el-form>
</template>

<script>
import BaseLayout from '@/views/layout/Base'
import DataTable from '@/components/DataTable'
import { JobShop } from '@/components/index'
import SelectProductForm from '@/components/CommonForm/SelectProductForm'
import UserSelect from '@/components/CommonForm/UserSelect'
import { getDict, parseTimeToYMDHMS } from '@/utils'
import { findByStore } from '@/api/after-sale/storehouseManage/warehouseManage'
import { findByStoreIdAndStorageId } from '@/api/after-sale/storehouseManage/positionManage'
import { getSupplierByStorId } from '@/api/after-sale/systemManage/supplier'
import {
  save,
  update,
  editDetailById,
  getStorageCode,
  findSourceCode
} from '@/api/pre-sale/boutiqueStock/putIn'

export default {
  components: { JobShop, BaseLayout, DataTable, SelectProductForm, UserSelect },
  data() {
    this.authConfig = {
      add: 'brandInStorage:save',
      edit: 'brandInStorage:update'
    }

    return {
      dialogVisible: false,
      dialogTitle: '精品选择',
      formData: {
        amount: 0,
        inStorageCode: '',
        storeId: '',
        storageId: '',
        supplierId: '',
        receiptsTime: parseTimeToYMDHMS(new Date()),
        inStorageType: '',
        workOrderCode: '',
        remark: '',
        userName: '',
        phone: '',
        partsList: [],
        partsTotal: 0
      },
      tableColumns: [
        { name: '精品编号', value: 'partsCode', type: 'text' },
        { name: '精品名称', value: 'partsName', type: 'text' },
        { name: '一级类别', value: 'partsType', type: 'text' },
        { name: '二级类别', value: 'partsUnit', type: 'text' },
        {
          name: '配件仓位',
          filterable: true,
          value: 'storageSiteId',
          type: 'select',
          options: this.storageSiteList,
          action: this.storageSiteChang
        },
        { name: '仓位编号', value: 'storageSiteCode', type: 'text' },
        {
          name: '入库数量',
          value: 'inStorageNum',
          type: 'inputNumber',
          maxFiledName: 'purchaseNum',
          action: this.calcData
        },
        { name: '库存数量', value: 'all', type: 'text' },
        { name: '已存储数', value: 'alreadyNum', type: 'text' },
        { name: '可增加库存', value: 'num', type: 'text' },
        { name: '采购成本', value: 'purchasePrice', type: 'text' },
        {
          name: '销售价',
          value: 'storagePrice',
          type: 'inputNumber',
          maxFiled: Number.MAX_VALUE,
          action: this.calcData
        },
        { name: '总金额', value: 'amount', type: 'text' }
      ],
      supplierList: [],
      storageList: [], // 仓库
      storageSiteList: [], // 仓位
      showProductTable: false,
      rules: {
        storageId: [
          { required: true, message: '请选择入库仓库' }
        ]
      }
    }
  },
  computed: {
    tableDataMap() {
      const map = {}
      this.formData.partsList.forEach((item, index) => {
        map[item.partsId] = index
      })
      return map
    },
    storeId() {
      return this.formData.storeId
    }
  },
  watch: {
    storeId() {
      this.requestSupplierList()
      this.requestStorageList()
    }
  },
  methods: {
    sourceCodeBlur() {
      const { inStorageType, workOrderCode } = this.formData
      if (inStorageType && workOrderCode) {
        findSourceCode(inStorageType, workOrderCode).then(res => {
          const { purchaseSupplierId, partsList = [] } = res.data || {}
          this.formData.supplierId = purchaseSupplierId
          if (partsList.length > 0) {
            const tempList = []

            partsList.forEach(item => {
              const num = item.purchaseNum || 0
              const price = item.purchasePrice

              tempList.push({
                amount: num * price,
                partsCode: item.partsCode,
                partsId: item.partsId,
                partsName: item.partsName,
                partsType: item.partsType,
                partsUnit: item.partsUnit,
                purchasePrice: price,
                internalNum: item.internalNum,
                inStorageNum: num,
                purchaseNum: num,
                storagePrice: price,
                storageSiteId: '',
                storageSiteCode: '',
                storageSiteName: '',
                num: 0, // 可增加库存
                alreadyNum: 0, // 已存储数
                all: 0 // 库存数量
              })
            })
            this.formData.partsList = tempList
            this.calcCountData()
          }
        })
      }
    },
    addProductHandle() {
      this.showProductTable = true
      this.dialogVisible = true
    },
    handleDataDelete(row, $index) {
      this.formData.partsList.splice($index, 1)
      this.calcCountData()
    },
    submitHandle() {
      const method = this.$route.params.id == 0 ? save : update
      this.$refs.formRef.validate(valid => {
        if (valid) {
          method(this.formData).then(res => {
            const length = this.$store.state.tagsView.visitedViews.length
            this.$store.dispatch('delVisitedViews', this.$route)
            if (length == 2) {
              this.$router.replace({ path: '/' })
            } else {
              this.$router.go(-1)
            }
          })
        }
      })
    },
    confirmSelectHandle(selection) {
      const tableList = []
      selection.forEach(item => {
        if (!this.tableDataMap[item.id]) {
          const price = item.currentPrice || 0
          tableList.push({
            amount: 0,
            partsCode: item.orderNo,
            partsId: item.id,
            partsName: item.name,
            partsType: item.appLargeOne,
            partsUnit: item.appLargeTwo,
            purchasePrice: price,
            internalNum: 0,
            storagePrice: price,
            storageSiteId: '',
            storageSiteCode: '',
            storageSiteName: '',
            alreadyNum: 0,
            num: 0,
            all: 0,
            inStorageNum: 0
          })
        }
      })
      this.formData.partsList.push(...tableList)
      this.calcCountData()
      this.dialogClose()
    },
    // 仓位改变
    storageSiteChang(row) {
      const { storageSiteId } = row
      if (storageSiteId) {
        const storageSite = this.storageSiteList.find(item => item.id == storageSiteId)
        row.storageSiteCode = storageSite.storageSiteCode
        row.storageSiteName = storageSite.storageSiteName
        row.alreadyNum = storageSite.alreadyNum
        row.num = storageSite.num
        row.all = storageSite.alreadyNum + storageSite.num
      } else {
        row.storageSiteCode = ''
        row.storageSiteName = ''
        row.alreadyNum = 0
        row.num = 0
        row.all = 0
      }
    },
    // 计算当前数据
    calcData(row) {
      const { storagePrice, inStorageNum } = row
      row.amount = inStorageNum * storagePrice
      this.calcCountData()
    },
    // 统计所有数据
    calcCountData() {
      let amount = 0 // 总金额
      let inStorageNum = 0 // 总数量

      this.formData.partsList.forEach(item => {
        amount += item.amount || 0
        inStorageNum += item.inStorageNum || 0
      })
      this.formData.amount = amount
      this.formData.partsTotal = inStorageNum
    },
    // 负责人选择
    userNameHChange(item) {
      this.formData.userName = item.userName
      this.formData.phone = item.phone
    },
    // 请求编辑详情
    requestEditDetail(id) {
      editDetailById(id).then(res => {
        Object.assign(this.formData, res.data)
        const { storeId, storageId } = this.formData
        this.requestStorageSiteList(storeId, storageId)
      })
    },
    // 请求编码
    requestCode() {
      getStorageCode().then(res => {
        this.formData.inStorageCode = res.data
      })
    },
    // 供应商改变
    supplierChange(value) {
      // this.formData.supplierUserName = ''
      // this.formData.supplierPhone = ''
      // this.requestSupplierDetail(value)
    },
    // 请求 供应商
    requestSupplierList() {
      const { storeId } = this.formData
      if (!storeId) {
        return
      }
      // this.formData.purchaseSupplierId = ''
      // this.formData.supplierUserName = ''
      // this.formData.supplierPhone = ''
      getSupplierByStorId(this.storeId, '精品供应商').then(res => {
        this.supplierList = res.data || []
      })
    },
    // 根据门店请求仓库
    requestStorageList() {
      if (!this.formData.storeId) {
        return
      }
      findByStore(this.formData.storeId).then(res => {
        this.storageList = res.data

        if (this.formData.storageId) {
          const data = res.data.find(item => item.id == this.formData.storageId)
          if (!data) {
            this.formData.storageId = ''
          }
        }
      })
    },
    // 请求仓位信息
    requestStorageSiteList() {
      const { storeId, storageId } = this.formData
      if (!storeId || !storageId) {
        return
      }
      findByStoreIdAndStorageId(storeId, storageId).then(res => {
        const data = res.data
        data.forEach(item => {
          item.value = item.storageSiteName
        })
        this.tableColumns[4].options = data
        this.storageSiteList = data
      })
    },
    dialogClose() {
      this.showProductTable = false
      this.dialogVisible = false
    }
  },
  created() {
    this.dict = getDict(['精品入库类型'])
  },
  mounted() {
    const { id, inStorageType, sourceCode } = this.$route.params
    this.formData.inStorageType = inStorageType
    this.formData.workOrderCode = sourceCode == 0 ? '' : sourceCode
    if (id != 0) {
      this.requestEditDetail(id)
    } else {
      this.requestCode()
      this.sourceCodeBlur()
    }
  }
}
</script>

<style></style>
